import navDatas from "../../../datas/navDatas.js"
import Ajax from "../../../utlis/Ajax.js"

export default class Nav {
  constructor(obj) {
    this.nav = document.querySelector("nav")
    this.head = document.querySelector("head")
    this.navFrag = document.createDocumentFragment()
    this.style = document.createElement("style")

    let main = document.querySelector("main")
    this.aside = main.querySelector("aside")
    this.article = main.querySelector("article")
    this.asideCatch = {}

    this.article = document.querySelector("article")
    //接收处理组件的结果对象
    this.obj = obj
  }
  init() {
    this.render()

    this.bindEvent()

    //初始化左侧按钮
    this.creatAsideItem()

    // 直接在初始化左侧按钮的时候 初始化一个组件
    // this.renderComponent();
  }

  render() {
    //根据数据渲染对应的nav
    this.renderNav(navDatas)

    //默认渲染css
    // this.renderStyle();
  }

  creatNavItem(data) {
    let a = document.createElement("a")
    a.href = `javascript:;`
    a.innerHTML = data
    this.navFrag.appendChild(a)
  }
  renderNav(navDatas) {
    for (let navData in navDatas) {
      this.creatNavItem(navData)
    }
    this.nav.appendChild(this.navFrag)
  }

  bindEvent() {
    this.nav.addEventListener("click", this.onNavClick.bind(this), false)
    this.aside.addEventListener("click", this.onAsideClick.bind(this), false)
  }
  onNavClick(ev) {
    let item = ev.target.innerHTML
    if (!item.includes("<a")) {
      this.creatAsideItem(item)
    }
  }

  creatAsideItem(item = "games") {
    if (!this.asideCatch[item]) {
      let str = ""
      for (let component in navDatas[item]) {
        str += `<button data-parent="${item}" data-name="${component}">${navDatas[item][component]}</button>`
      }
      this.asideCatch[item] = str
    }
    this.renderAsideItem(this.asideCatch[item])

    //初始化一个组件 只作为切换 aside的初始化 展示第一个 具体的切换在aside的事件监听里
    let componentName = Object.keys(navDatas[item])[0]
    this.renderComponent(item, componentName)
  }
  renderAsideItem(res) {
    this.aside.innerHTML = res
  }

  onAsideClick(ev) {
    if (ev.target.tagName === "BUTTON") {
      let componentName = ev.target.getAttribute("data-name")
      let parent = ev.target.getAttribute("data-parent")
      console.log(parent, componentName)
      this.renderComponent(parent, componentName)
    }
  }
  renderComponent(parent, componentName) {
    Ajax.load(`../../../Components/${parent}/${componentName}/index.html`, "article", templet => {
      this.article.innerHTML = templet
      this.obj[componentName]().init()
      this.renderStyle(parent, componentName)
    })
  }

  renderStyle(parent, componentName) {
    Ajax.get(`../../../Components/${parent}/${componentName}/css/style.css`, res => {
      this.style.innerHTML = res
      this.head.appendChild(this.style)
    })
  }
}
